/*
@Time : 2020/6/22 16:47
@Author : yaodongpo
@File : sql.go
@Software: GoLand
*/
package gen

import (
	"database/sql"
	"fmt"
	"github.com/astaxie/beego"
	_ "github.com/go-sql-driver/mysql"
)

var sqlSchemaDatabase = fmt.Sprintf("%s:%s@tcp(%s:%s)/information_schema",
	beego.AppConfig.String("mysql::user_name"), beego.AppConfig.String("mysql::password"),
	beego.AppConfig.String("mysql::host"), beego.AppConfig.String("mysql::port"))

var SchemaPool *sql.DB
func init()  {
	var err error
	SchemaPool, err = sql.Open("mysql", sqlSchemaDatabase)
	CheckErr(err)
	//defer SchemaPool.Close()
	SchemaPool.SetConnMaxLifetime(0)
	SchemaPool.SetMaxIdleConns(3)
	SchemaPool.SetMaxOpenConns(3)
}

func GetListBySqlAndConnStr(query string) (list []map[string]string) {
	var err error
	err = SchemaPool.Ping()
	CheckErr(err)
	if rows, err := SchemaPool.Query(query); err != nil {
		CheckErr(err)
	} else {
		defer rows.Close()
		columns, _ := rows.Columns()
		//多少个字段
		length := len(columns)
		//每一行字段的值
		values := make([]sql.RawBytes, length)
		//保存的是values的内存地址
		pointer := make([]interface{}, length)
		//
		for i := 0; i < length; i++ {
			pointer[i] = &values[i]
		}
		//
		for rows.Next() {
			//把参数展开，把每一行的值存到指定的内存地址去，循环覆盖，values也就跟着被赋值了
			rows.Scan(pointer...)
			//每一行
			row := make(map[string]string)
			for i := 0; i < length; i++ {
				row[columns[i]] = string(values[i])
			}
			list = append(list, row)
		}
	}
	return
}
